<template>
  <div class="addOrEditCallServiceSkillGroup">
    <ul class="tab">
      <li class="tab-item" :class="[active === 1 ? 'tab-item-active' : '']" @click="tabChange(1)">{{$t('callServiceSkillGroup.callServiceSkillGroup41')}}</li>
      <li class="tab-item" :class="[active === 2 ? 'tab-item-active' : '']" @click="tabChange(2)" v-show="!isNewConfig">{{$t('callServiceSkillGroup.callServiceSkillGroup42')}}</li>
      <li class="tab-item" :class="[active === 3 ? 'tab-item-active' : '']" @click="tabChange(3)" v-show="!isNewConfig">{{$t('callServiceSkillGroup.callServiceSkillGroup43')}}</li>
      <li class="tab-item" :class="[active === 4 ? 'tab-item-active' : '']" @click="tabChange(4)" v-show="!isNewConfig">{{$t('callServiceSkillGroup.callServiceSkillGroup44')}}</li>
    </ul>
    <div class="form_box" v-loading="loading">
      <el-form :model="skillInfoForm" label-position="top" :rules="rules" ref="skillInfoForm" label-width="100px">
        <div class="cont" v-show="active === 1">
        <p class="prompt">
          {{$t('callServiceSkillGroup.callServiceSkillGroup7')}}
          </br><span v-if="isNewConfig">{{$t('callServiceSkillGroup.callServiceSkillGroup8')}}</span>
        </p>
          <div class="skill-group-item">
            <p>PBX</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.PBX" :disabled="!!skillInfo.Exten" @change="PBXchange">
              <el-option
                v-for="item in pbxs"
                :label="item.NickName + ' (' +item.PBX + ')'"
                :value="item.PBX">
              </el-option>
            </el-select>
          </div>
          <div class="skill-group-item">
            <el-form-item :label="$t('callServiceSkillGroup.callServiceSkillGroup9')" prop="DisplayName">
              <el-input v-model.trim="skillInfoForm.DisplayName" :maxlength="16"></el-input>
            </el-form-item>
          </div>
          <div v-show="skillInfo.Exten" class="skill-group-item">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup10')}}</p>
            <el-input v-model.trim="skillInfoForm.Exten" disabled></el-input>
          </div>
          <AgentAssign v-if="isNewConfigAgent" :forChannelConfig="true" :PBX="PBXForAgent" :checkedAgentsOfChannelConfig="AssignMembersArr" @assign-change="handleAssignChange"></AgentAssign>
          <div class="skill-group-item" v-show="!isNewConfig">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup11')}}</p>
            <el-radio-group v-model="skillInfoForm.SayExten">
              <el-radio class="radio" :label="true">{{$t('public.yes')}}</el-radio>
              <el-radio class="radio" :label="false">{{$t('public.no')}}</el-radio>
            </el-radio-group>
          </div>
          <div v-show="skillInfo.Exten && !isNewConfig" class="skill-group-item">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup12')}}</p>
            <el-radio-group v-model="skillInfoForm.AgentExtenPoint">
              <el-radio class="radio" :label="true">{{$t('public.yes')}}</el-radio>
              <el-radio class="radio" :label="false">{{$t('public.no')}}</el-radio>
            </el-radio-group>
          </div>
          <div v-show="skillInfo.Exten && !isNewConfig" class="skill-group-item">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup13')}}</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.MusicClass">
              <el-option
                :label="$t('callServiceSkillGroup.callServiceSkillGroup14')"
                value="">
              </el-option>
              <el-option
                v-for="item in waitMusic"
                :label="item.DisplayName"
                :value="item.Filename">
              </el-option>
            </el-select>
          </div>
          <div v-show="skillInfo.Exten && !isNewConfig" class="skill-group-item">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup15')}}
              <questionToolTip :tipContent="$t('callServiceSkillGroup.callServiceSkillGroup16')"></questionToolTip>
            </p>
            <el-form-item prop="SayQueuePosition">
              <el-input v-model="skillInfoForm.SayQueuePosition">
                <template slot="append">{{$t('public.seconds')}}</template>
              </el-input>
            </el-form-item>
          </div>
          <div v-show="skillInfo.Exten && !isNewConfig" class="skill-group-item">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup17')}}</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.Music">
              <el-option
                :label="$t('callServiceSkillGroup.callServiceSkillGroup14')"
                value="">
              </el-option>
              <el-option
                v-for="item in ivrSoundOptions"
                :label="item.DisplayName"
                :value="item.Filename">
              </el-option>
            </el-select>
          </div>
          <div class='skill-group-item-row'>
            <div v-show="!isNewConfig" class='skill-group-item'>
              <p>{{$t('callServiceSkillGroup.callServiceSkillGroup18')}}</p>
              <div class='skill-group-item-ob-flex'>
                <div class='skill-group-item-ob-flex-ipt'>
                  <el-form-item prop="QueueWeight">
                    <el-input-number v-model="skillInfoForm.QueueWeight" :min="0" :max="99" controls-position="right"></el-input-number>
                  </el-form-item>
                </div>
                <div class='text'>
                  <p class='title'>{{$t('callServiceSkillGroup.callServiceSkillGroup19')}}</p>
                  <p>{{$t('callServiceSkillGroup.callServiceSkillGroup20')}}</p>
                </div>
              </div>
            </div>
            <div class="skill-group-item">
              <p>{{$t('callServiceSkillGroup.callServiceSkillGroup21')}}</p>
              <div class='skill-group-item-ob-flex'>
                <div class='skill-group-item-ob-flex-ipt'>
                  <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.Strategy">
                    <el-option
                      :label="$t('callServiceSkillGroup.callServiceSkillGroup22')"
                      value="rrmemory">
                    </el-option>
                    <el-option
                      :label="$t('callServiceSkillGroup.callServiceSkillGroup23')"
                      value="random">
                    </el-option>
                    <el-option
                      v-if="!isAdd && skillInfo.Strategy === 'fewestcalls'"
                      :label="$t('callServiceSkillGroup.callServiceSkillGroup24')"
                      :disabled="skillInfo.Strategy === 'fewestcalls'?true:false"
                      value="fewestcalls">
                    </el-option>
                    <el-option
                      :label="$t('callServiceSkillGroup.callServiceSkillGroup25')"
                      value="leastrecent">
                    </el-option>
                  </el-select>
                </div>
                <div class='text'>
                  <p class='title'>{{$t('callServiceSkillGroup.callServiceSkillGroup26')}}</p>
                  <p>{{$t('callServiceSkillGroup.callServiceSkillGroup27')}}</p>
                </div>
              </div>
            </div>
          </div>
           <div class="skill-group-item" v-show="!isNewConfig">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup28')}}</p>
            <el-radio-group v-model="skillInfoForm.JoinEmpty">
              <el-radio class="radio" :label="'1'">{{$t('public.yes')}}</el-radio>
              <el-radio class="radio" :label="'0'">{{$t('public.no')}}</el-radio>
            </el-radio-group>
           </div>
           <div class="skill-group-item" v-show="!isNewConfig && isShowNotransfer">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup74')}}<questionToolTip :tipContent="$t('callServiceSkillGroup.callServiceSkillGroup75')"></questionToolTip></p>
            <el-radio-group v-model="skillInfoForm.NotTransfer">
              <el-radio class="radio" :label="true">{{$t('public.yes')}}</el-radio>
              <el-radio class="radio" :label="false">{{$t('public.no')}}</el-radio>
            </el-radio-group>
           </div>
            <div class="skill-group-item">
              <p>{{$t('configLazyLoad.channel.enableRobotAgent')}}</p>
              <el-select v-model="skillInfoForm.Robot" filterable>
                <el-option
                  v-for="(item,index) in xbotList"
                  :key="item.Id"
                  :label="item.Nick"
                  :value="item.Id">
                </el-option>
              </el-select>
            </div>
          <br/>
          <h5 style="padding: 16px 0 12px 0;border-top: 1px solid #ccc;">
            {{$t('callServiceSkillGroup.callServiceSkillGroup29')}}
            <questionToolTip style="margin-left: 14px;" :tipContent="$t('callServiceSkillGroup.callServiceSkillGroup30')"></questionToolTip>
          </h5>
          <div class="skill-group-item" v-show="!isNewConfig">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup31')}}</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.KfBussinessTypeId">
              <el-option
                :label="$t('public.pleasePick1')"
                value="">
              </el-option>
              <el-option
                v-for="item in businessFlowOnly"      
                :disabled="item.status=='disable'"
                :key="item._id"
                :label="item.name"
                :value="'business_' + item._id">
              </el-option>
            </el-select>
          </div>
          <div class="skill-group-item" v-show="!isNewConfig">
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup32')}}</p>
            <el-select size="mini" v-model="skillInfoForm.CallinTypeId" multiple :placeholder="$t('public.pleasePick')">
              <el-option
                v-for="item in callUrls"
                :label="item.name"
                :value="'callUrls_' + item._id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="cont" v-show="active === 2">
          <p class="prompt">{{$t('callServiceSkillGroup.callServiceSkillGroup33')}}</p>
          <AgentAssign :openBatch="true" v-if="isShowAgentAssign && !isNewConfig" :forChannelConfig="true" :PBX="PBXForAgent" :checkedAgentsOfChannelConfig="AssignMembersArr" @assign-change="handleAssignChange"></AgentAssign>
        </div>
        <div class="cont" v-show="active === 3">
          <p class="prompt">{{$t('callServiceSkillGroup.callServiceSkillGroup34')}}</p>
          <div>
            <div style="width: 40%;display: inline-block;margin-right: 30px;">
              <el-form-item :label="$t('callServiceSkillGroup.callServiceSkillGroup35')" prop="WaitTime">
                <el-input v-model="skillInfoForm.WaitTime" :maxlength="5">
                  <template slot="append">{{$t('public.seconds')}}</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="width: 40%;display: inline-block;">
              <el-form-item :label="$t('callServiceSkillGroup.callServiceSkillGroup36')" prop="Timeout">
                <el-input v-model="skillInfoForm.Timeout" :maxlength="5">
                  <template slot="append">{{$t('public.seconds')}}</template>
                </el-input>
              </el-form-item>
            </div>
          </div>
        </div>
        <div class="cont" v-show="active === 4">
          <div>
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup37')}}</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.ToPeerTypeWhenQueueEmpty" @change="ToPeerTypeWhenQueueEmptyChange">
              <el-option
                v-for="item in toPeerTypeArr"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" filterable v-model="skillInfoForm.ToPeerWhenQueueEmpty">
              <el-option
                v-for="item in ToPeerTypeWhenQueueEmptyOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup38')}}</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.ToPeerTypeWhenWait" @change="ToPeerTypeWhenWaitChange">
              <el-option
                v-for="item in toPeerTypeArr"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" filterable v-model="skillInfoForm.ToPeerWhenWait">
              <el-option
                v-for="item in ToPeerWhenWaitOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup39')}}</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.ToPeerTypeWhenWaitTimeout" @change="ToPeerTypeWhenWaitTimeoutChange">
              <el-option
                v-for="item in toPeerTypeArr"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" filterable v-model="skillInfoForm.ToPeerWhenWaitTimeout">
              <el-option
                v-for="item in ToPeerWhenWaitTimeoutOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <p>{{$t('callServiceSkillGroup.callServiceSkillGroup40')}}</p>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" v-model="skillInfoForm.ToPeerTypeWhenHanguped" @change="ToPeerTypeWhenHangupedChange">
              <el-option
                v-for="item in toPeerTypeArr"
                v-if="item.TypeValue !== 'ivr_node_queue'"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" :placeholder="$t('public.pleasePick')" filterable v-model="skillInfoForm.ToPeerWhenHanguped">
              <el-option
                v-for="item in ToPeerWhenHangupedOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </el-form>
      <div class="btn_box">
        <el-button type="primary" class="primary_btn" @click="submit">{{$t('public.save')}}</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import AgentAssign from '@/components/public-modules/agent-assign/AgentAssign.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import {checkform} from '@/utils/validate'
  import questionToolTip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  export default {
    name: 'addOrEditCallServiceSkillGroup',
    data () {
      let checkSayQueuePosition = (rule, value, callback) => {
        if (!value && value !== 0) {
          return callback(new Error(this.$t('validate.required')))
        }
        if (checkform(value, 'Number')) {
          callback(new Error(this.$t('callServiceSkillGroup.callServiceSkillGroup47')))
        }
        setTimeout(() => {
          if (value < 15 && value > 0 || value < 0) {
            callback(new Error(this.$t('callServiceSkillGroup.callServiceSkillGroup16')))
          } else {
            callback()
          }
        }, 100)
      }
      let validate1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        }else if (value < 1) {
          callback(new Error(this.$t('callServiceSkillGroup.callServiceSkillGroup46')))
        } else if (checkform(value, 'Number')) {
          callback(new Error(this.$t('callServiceSkillGroup.callServiceSkillGroup47')))
        } else {
          callback()
        }
      }
      let checkWaitTime = (rule, value, callback) => {
        if (!value && value !== 0) {
          return callback(new Error(this.$t('validate.required')))
        }
        if (value < 1) {
          callback(new Error(this.$t('callServiceSkillGroup.callServiceSkillGroup46')))
        } else {
          callback()
        }
      }
      let checkSayQueueWeightProp = (rule, value, callback) => {
        if (!value && value !== 0) {
          return callback(new Error(this.$t('validate.required')))
        }
        if (value < 0) {
          callback(new Error(this.$t('callServiceSkillGroup.callServiceSkillGroup48')))
        } else if (value > 99) {
          callback(new Error(this.$t('callServiceSkillGroup.callServiceSkillGroup49')))
        } else {
          callback()
        }
      }
      return {
        xRobot: '',
        xbotList: [],
        isShowNotransfer: false,
        isShowAgentAssign: false,  //   默认不加载选择座席组件  切换到坐席分配在渲染  避免卡顿
        isNewConfigAgent: false,
        isNewConfig: false, // 是否为新设置
        active: 1,
        PBXForAgent: '',  //  向 座席分配组件里  传的 pbx
        loading: false,
        callUrls: [],
        agents: [],
        pbxs: [],
        businessFlowOnly: [],
        AssignMembersArr: [],
        skillInfoForm: {
          Robot:this.skillInfo.Robot || '',
          PBX: '',
          Exten: this.skillInfo.Exten || '',   //  技能组号
          SayExten: this.skillInfo.SayExten || false,  //   是否启用报工号
          KfBussinessTypeId: '',  //   来电弹屏
          CallinTypeId: [],   //  对接弹屏
          MusicClass: '',   //   等待音乐
          Music: '',    //    进入技能组提示音
          DisplayName: this.skillInfo.DisplayName || '',    //    技能组名称
          Strategy: this.skillInfo.Strategy || 'rrmemory',  //   座席分配策略
          AgentExtenPoint: this.skillInfo.AgentExtenPoint || false,   //   是否启用报工号后的提示音
          SayQueuePosition: this.skillInfo.SayQueuePosition || 0,  //    播报排队位置时间间隔
          JoinEmpty: this.skillInfo.JoinEmpty || '0',  //   无空闲座席时立即流转
          WaitTime: Number(this.skillInfo.WaitTime) || 120,  //    等待时长
          Timeout: Number(this.skillInfo.Timeout) || 30,   //    座席振铃时长
          MemberToken: this.skillInfo.MemberToken || [],    //  分配座席
          ToPeerTypeWhenQueueEmpty: this.skillInfo.ToPeerTypeWhenQueueEmpty || 'system',  //  技能组为空时转向
          ToPeerWhenQueueEmpty: this.skillInfo.ToPeerWhenQueueEmpty || '0',  //  技能组为空时转向
          ToPeerTypeWhenWait: this.skillInfo.ToPeerTypeWhenWait || 'system',  //  正在等待时转向
          ToPeerWhenWait: this.skillInfo.ToPeerWhenWait || '0',  //  正在等待时转向
          ToPeerTypeWhenWaitTimeout: this.skillInfo.ToPeerTypeWhenWaitTimeout || 'system',  //  等待超时转向
          ToPeerWhenWaitTimeout: this.skillInfo.ToPeerWhenWaitTimeout || '0',  //  等待超时转向
          ToPeerTypeWhenHanguped: this.skillInfo.ToPeerTypeWhenHanguped || 'system',    //   通话结束后转向
          ToPeerWhenHanguped: this.skillInfo.ToPeerWhenHanguped || '0',    //   通话结束后转向
          QueueWeight: this.skillInfo.QueueWeight || 0,
          NotTransfer: this.skillInfo.NotTransfer || false
        },
        toPeerTypeArr: [
          {TypeValue: 'system', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup53')},
          {TypeValue: 'ivr_node_queue', TypeName: this.$t('public.queues')},
          {TypeValue: 'account_user', TypeName: this.$t('public.agent')},
          {TypeValue: 'ivr_node_announcement', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup54')},
          {TypeValue: 'ivr_node_text_announcement', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup55')},
          {TypeValue: 'ivr_node_ivr', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup56')},
          {TypeValue: 'ivr_node_encrypt_md5', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup57')},
          {TypeValue: 'ivr_node_validation', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup58')},
          {TypeValue: 'ivr_node_assignment', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup59')},
          {TypeValue: 'ivr_node_route', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup60')},
          {TypeValue: 'ivr_node_ivr_menu', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup61')},
          {TypeValue: 'ivr_node_call_url', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup62')},
          {TypeValue: 'ivr_node_date', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup63')},
          {TypeValue: 'ivr_node_twowaycall', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup64')},
          {TypeValue: 'ivr_node_asr', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup65')},
          {TypeValue: 'ivr_node_voice_mail', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup66')},
          {TypeValue: 'ivr_node_room', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup67')},
          {TypeValue: 'ivr_node_satisfaction', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup68')},
          {TypeValue: 'ivr_node_superDialJobNum', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup69')},
          {TypeValue: 'ivr_node_extension_peer', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup70')}
        ],
        systemPeerTypeArr: [
          {name: this.$t('softPhoneBar.hangup'), value: '0'},
          {name: this.$t('cti.satiSearch'), value: '1'},
          {name: this.$t('callServiceSkillGroup.callServiceSkillGroup71'), value: '2'}
        ],
        sounds: [],
        ivrSoundOptions: [],
        waitMusic: [],
        ToPeerTypeWhenQueueEmptyOptions: [],
        ToPeerWhenWaitOptions: [],
        ToPeerWhenWaitTimeoutOptions: [],
        ToPeerWhenHangupedOptions: [],
        rules: {
          DisplayName: [
            { required: true, max: 16, message: this.$t('callServiceSkillGroup.callServiceSkillGroup50'), trigger: 'blur' }
          ],
          WaitTime: [
            { required: true, validator: validate1, trigger: 'blur' }
          ],
          Timeout: [
            { required: true, validator: validate1, trigger: 'blur' }
          ],
          SayQueuePosition: [
            { required: true, validator: checkSayQueuePosition, trigger: 'blur' }
          ],
          QueueWeight: [
            { required: true, validator: checkSayQueueWeightProp, trigger: 'blur' }
          ]
        }
      }
    },
    props: {
      skillInfo: {
        type: Object,
        default: function () {
          return {}
        }
      },
      isAdd: Boolean
    },
    watch: {
      skillInfo () {
        this.skillInfoForm.PBX = this.skillInfo.PBX || this.pbxs[0].PBX
        // this.getIsShowTrans()
        this.PBXForAgent = this.skillInfoForm.PBX
        this.skillInfoForm.Exten = this.skillInfo.Exten || ''
        this.skillInfoForm.SayExten = this.skillInfo.SayExten || false
        this.skillInfoForm.QueueWeight = this.skillInfo.QueueWeight || 0
        this.skillInfoForm.Robot = this.skillInfo.Robot || ''
        //      多个来电弹屏 处理
        this.skillInfoForm.CallinTypeId = []
        if (typeof (this.skillInfo.KfBussinessTypeId) === 'undefined') {   //  老版来电弹屏设置
          this.skillInfoForm.KfBussinessTypeId = this.skillInfo.BussinessTypeId || ''
          if (this.skillInfo.BussinessTypeId) {
            let interfaceId = this.skillInfo.BussinessTypeId.split('_')[1]
            for (let y = 0; y < this.callUrls.length; y++) {
              if (this.callUrls[y]._id === interfaceId) {
                this.skillInfoForm.KfBussinessTypeId = ''
                this.skillInfoForm.CallinTypeId.push(this.skillInfo.BussinessTypeId)
                break
              }
            }
          }
        } else {
          this.skillInfoForm.KfBussinessTypeId = this.skillInfo.KfBussinessTypeId || ''
          for (let i = 0; i < this.callUrls.length; i++) {
            for (let j = 0; j < this.skillInfo.CallinTypeId.length; j++) {
              if (this.callUrls[i]._id === this.skillInfo.CallinTypeId[j].split('_')[1]) {
                this.skillInfoForm.CallinTypeId.push(this.skillInfo.CallinTypeId[j])
              }
            }
          }
//          this.skillInfoForm.CallinTypeId = this.skillInfo.CallinTypeId
        }
        if (this.skillInfo.MusicClass) {
          this.skillInfoForm.MusicClass = this.skillInfo.MusicClass.split('.')[1] === 'wav' ? this.skillInfo.MusicClass : this.skillInfo.MusicClass + '.wav'
        } else {
          this.skillInfoForm.MusicClass = ''
        }
        if (this.skillInfo.Music) {
          this.skillInfoForm.Music = this.skillInfo.Music.split('.')[1] === 'wav' ? this.skillInfo.Music : this.skillInfo.Music + '.wav'
        } else {
          this.skillInfoForm.Music = ''
        }
        this.skillInfoForm.DisplayName = this.skillInfo.DisplayName || ''
        this.skillInfoForm.Strategy = this.skillInfo.Strategy || 'rrmemory'
        this.skillInfoForm.AgentExtenPoint = this.skillInfo.AgentExtenPoint || false
        this.skillInfoForm.SayQueuePosition = this.skillInfo.SayQueuePosition || 0
        this.skillInfoForm.JoinEmpty = this.skillInfo.JoinEmpty || '0'
        this.skillInfoForm.NotTransfer = this.skillInfo.NotTransfer || false
        this.skillInfoForm.WaitTime = Number(this.skillInfo.WaitTime) || 120
        this.skillInfoForm.Timeout = Number(this.skillInfo.Timeout) || 30
//        this.skillInfoForm.MemberToken = this.skillInfo.MemberToken || []   //   座席
        this.skillInfoForm.ToPeerTypeWhenQueueEmpty = this.skillInfo.ToPeerTypeWhenQueueEmpty || 'system'
        // this.ToPeerTypeWhenQueueEmptyChange(this.skillInfo.ToPeerTypeWhenQueueEmpty)
        this.skillInfoForm.ToPeerWhenQueueEmpty = this.skillInfo.ToPeerWhenQueueEmpty || '0'
        this.skillInfoForm.ToPeerTypeWhenWait = this.skillInfo.ToPeerTypeWhenWait || 'system'
        this.skillInfoForm.ToPeerWhenWait = this.skillInfo.ToPeerWhenWait || '0'
        // this.ToPeerTypeWhenWaitChange(this.skillInfo.ToPeerTypeWhenWait)
        this.skillInfoForm.ToPeerTypeWhenWaitTimeout = this.skillInfo.ToPeerTypeWhenWaitTimeout || 'system'
        this.skillInfoForm.ToPeerWhenWaitTimeout = this.skillInfo.ToPeerWhenWaitTimeout || '0'
        // this.ToPeerTypeWhenWaitTimeoutChange(this.skillInfo.ToPeerTypeWhenWaitTimeout)
        this.skillInfoForm.ToPeerTypeWhenHanguped = this.skillInfo.ToPeerTypeWhenHanguped || 'system'
        this.skillInfoForm.ToPeerWhenHanguped = this.skillInfo.ToPeerWhenHanguped || '0'
        // this.ToPeerTypeWhenHangupedChange(this.skillInfo.ToPeerTypeWhenHanguped)
        this.getAssignMembersArr()
        this.tabChange(1)
        this.refreshSounds()
      },
      isAdd (data) {
        if (data) {
          this.resetSkillInfo()
        }
      },
      PBXForAgent () {
        this.getIsShowTrans()
      }
    },
    methods: {
      getXbotList () {
        this.$store.dispatch('queryM7AIRobot', {}).then(res => {
          if (res && res.success && res.data && res.data.length > 0) {
            const resArr = res.data.filter(item => item.robotType === 'xbot')
            resArr.unshift({ Nick: '请选择', Id: '' })
            this.xbotList = resArr
          }
        })
      },
      PBXchange () {
        this.loading = true
        if (this.skillInfo.Exten) {
          this.loading = false
          this.PBXForAgent = this.skillInfoForm.PBX
          return
        }
        let data = {}
        data.Account = this.$store.state.session.account.account
        data.PBX = this.skillInfoForm.PBX
        if (!this.$store.state.session.ivrMap[data.PBX]) {
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(() => {
            this.loading = false
            this.PBXForAgent = this.skillInfoForm.PBX
          })
        } else {
          this.loading = false
          this.PBXForAgent = this.skillInfoForm.PBX
        }
        this.AssignMembersArr = []
        this.resetSkillInfo()
      },
//      重置技能组 信息
      resetSkillInfo () {
        this.skillInfoForm.ToPeerTypeWhenQueueEmpty = 'system'
        this.skillInfoForm.ToPeerWhenQueueEmpty = '0'
        this.skillInfoForm.ToPeerTypeWhenWait = 'system'
        this.skillInfoForm.ToPeerWhenWait = '0'
        this.skillInfoForm.ToPeerTypeWhenWaitTimeout = 'system'
        this.skillInfoForm.ToPeerWhenWaitTimeout = '0'
        this.skillInfoForm.ToPeerTypeWhenHanguped = 'system'
        this.skillInfoForm.ToPeerWhenHanguped = '0'
      },
      tabChange (val) {
        this.active = val
        if (val === 1 && this.isNewConfig) {
          this.initAgent()
        }
        if (val === 2) {
          this.initAgent()
        }
        if (val === 4) {
          this.initSelect()
        }
      },
//      分配座席回显
      getAssignMembersArr () {
        this.skillInfoForm.MemberToken = []
        if (!this.skillInfo.AssignMembers || this.skillInfo.AssignMembers.length === 0) {
          this.AssignMembersArr = []
          return
        }
        let agentArr = []
        let agents = this.$store.getters.agents
        this.skillInfo.AssignMembers.forEach(one => {
          this.skillInfoForm.MemberToken.push(one.agentID + ':' + one.penalty)  //  先预存技能组 座席的信息  防止不初始化坐席分配组件带来的  数据为空问题
          if (agents[one.agentID]) {
            agentArr.push({_id: agents[one.agentID]._id, displayName: agents[one.agentID].displayName, exten: agents[one.agentID].exten, count: one.penalty})
          }
        })
        let hash = {}
        agentArr = agentArr.reduce(function (item, next) {
          hash[next._id] ? '' : hash[next._id] = true && item.push(next)
          return item
        }, [])
        this.AssignMembersArr = agentArr
      },
      flowOptionsChange (val, options) {
        let toPeerArr = this.$store.state.session.ivrMap[this.skillInfoForm.PBX].data[val]
        if (!val || val === 'system') {
          this.systemPeerTypeArr.forEach(item => {
            options.push({name: item.name, value: item.value})
          })
        } else {
          options.push({name: this.$t('public.pleasePick1'), value: ''})
          if (toPeerArr) {
            if (val === 'account_user') {
              toPeerArr.forEach(item => {
                options.push({name: item.displayName, value: item._id})
              })
            } else if(val === 'ivr_node_satisfaction') {
              toPeerArr.forEach(item => {
                if (item.SatisfactionGarde !== 'child') {
                  options.push({name: item.DisplayName, value: item.Exten})
                }
              })
            } else {
              toPeerArr.forEach(item => {
                options.push({name: item.DisplayName, value: item.Exten})
              })
            }
          }
        }
      },
      //  流转  选择框 change
      ToPeerTypeWhenQueueEmptyChange (val) {
        this.$store.dispatch('getAssignNodesByPbx', {Account: this.$store.state.session.account.account, PBX: this.skillInfoForm.PBX, type: val}).then(res => {
          this.ToPeerTypeWhenQueueEmptyOptions = []
          this.flowOptionsChange(val, this.ToPeerTypeWhenQueueEmptyOptions)
          if (val === this.skillInfo.ToPeerTypeWhenQueueEmpty) {
            this.skillInfoForm.ToPeerWhenQueueEmpty = this.skillInfo.ToPeerWhenQueueEmpty || this.ToPeerTypeWhenQueueEmptyOptions[0].value
          } else {
            this.skillInfoForm.ToPeerWhenQueueEmpty = this.ToPeerTypeWhenQueueEmptyOptions[0].value
          }
        })
      },
      ToPeerTypeWhenWaitChange (val) {
        this.$store.dispatch('getAssignNodesByPbx', {Account: this.$store.state.session.account.account, PBX: this.skillInfoForm.PBX, type: val}).then(res => {
          this.ToPeerWhenWaitOptions = []
          this.flowOptionsChange(val, this.ToPeerWhenWaitOptions)
          if (val === this.skillInfo.ToPeerTypeWhenWait) {
            this.skillInfoForm.ToPeerWhenWait = this.skillInfo.ToPeerWhenWait || this.ToPeerWhenWaitOptions[0].value
          } else {
            this.skillInfoForm.ToPeerWhenWait = this.ToPeerWhenWaitOptions[0].value
          }
        })
      },
      ToPeerTypeWhenWaitTimeoutChange (val) {
        this.$store.dispatch('getAssignNodesByPbx', {Account: this.$store.state.session.account.account, PBX: this.skillInfoForm.PBX, type: val}).then(res => {
          this.ToPeerWhenWaitTimeoutOptions = []
          this.flowOptionsChange(val, this.ToPeerWhenWaitTimeoutOptions)
          if (val === this.skillInfo.ToPeerTypeWhenWaitTimeout) {
            this.skillInfoForm.ToPeerWhenWaitTimeout = this.skillInfo.ToPeerWhenWaitTimeout || this.ToPeerWhenWaitTimeoutOptions[0].value
          } else {
            this.skillInfoForm.ToPeerWhenWaitTimeout = this.ToPeerWhenWaitTimeoutOptions[0].value
          }
        })
      },
      ToPeerTypeWhenHangupedChange (val) {
        this.$store.dispatch('getAssignNodesByPbx', {Account: this.$store.state.session.account.account, PBX: this.skillInfoForm.PBX, type: val}).then(res => {
          this.ToPeerWhenHangupedOptions = []
          this.flowOptionsChange(val, this.ToPeerWhenHangupedOptions)
          if (val === this.skillInfo.ToPeerTypeWhenHanguped) {
            this.skillInfoForm.ToPeerWhenHanguped = this.skillInfo.ToPeerWhenHanguped || this.ToPeerWhenHangupedOptions[0].value
          } else {
            this.skillInfoForm.ToPeerWhenHanguped = this.ToPeerWhenHangupedOptions[0].value
          }
        })
      },
//      分配座席 组件 抛出事件
      handleAssignChange (agentCount) {
        let agentCounts = agentCount
        this.skillInfoForm.MemberToken = []
        agentCounts.forEach(item => {
          this.skillInfoForm.MemberToken.push(item.agent + ':' + item.count)
        })
      },
      /**
       * 添加/修改技能组
       * @param {Object} data
       * @param {String} data.Account 账户id
       * @param {String} data.PBX pbx
       * @param {String} data.action 'add' => 添加，'update' => 修改
       * @param {String} data.State 是否启用（没找到使用的地方，传'enable'）
       * @param {String} data.Type 类型，'normal'
       * @param {String} data.DisplayName 名称
       * @param {String} data.Strategy 'rrmemory'
       * @param {Boolean} data.SayExten 是否启用报工号
       * @param {Boolean} data.AgentExtenPoint 是否启用报工号后的提示音
       * @param {String} data.JoinEmpty 无空闲座席时立刻流转，'1' => 是，'0' => 否
       * @param {Boolean} data.NotTransfer 禁止座席转入技能组 true => 是，false => 否
       * @param {String|Number} data.SayQueuePosition 播报排队位置时间间隔，'0' => 不播报
       * @param {String} data.BussinessTypeId 来电弹屏，'business_${工单流程id}'，'callUrls_${来电弹屏id}'
       * @param {String} data.MusicClass 等待语音
       * @param {String} data.Music 进入技能组提示音
       * @param {String|Number} data.WaitTime 等待时长
       * @param {String|Number} data.Timeout 座席振铃时长
       * @param {String} data.ToPeerTypeWhenQueueEmpty 技能组为空时转向类型
       * @param {String} data.ToPeerWhenQueueEmpty 技能组为空时转向
       * @param {String} data.ToPeerTypeWhenWait 正在等待时转向类型
       * @param {String} data.ToPeerWhenWait 正在等待时转向
       * @param {String} data.ToPeerTypeWhenWaitTimeout 等待超时转向类型
       * @param {String} data.ToPeerWhenWaitTimeout 等待超时转向
       * @param {String} data.ToPeerTypeWhenHanguped 通话结束后转向类型
       * @param {String} data.ToPeerWhenHanguped 通话结束后转向
       * @param {String} data.MemberToken 座席分配，['${座席id}:${优先级}']
       * ---- 以下为修改时要另外提供的 ----
       * @param {String} [data._id] 技能组id
       * @param {String} [data.Exten] 技能组号
       */
      submit () {
        if (this.skillInfoForm.CallinTypeId && this.skillInfoForm.CallinTypeId.length > 2) {
          this.$message.error(this.$t('callServiceSkillGroup.callServiceSkillGroup51'))
          return false
        }
        this.$refs.skillInfoForm.validate((valid) => {
          if (valid) {
            let MemberToken = deepClone(this.skillInfoForm.MemberToken)
            let data = deepClone(this.skillInfoForm)
            data.MemberToken = JSON.stringify(MemberToken)
            data.Account = this.$store.state.session.account.account
            data.State = 'enable'
            data.Type = 'normal'
            if (!this.skillInfo._id) {
              delete data._id
              delete data.Exten
              data.action = 'add'
            } else {
              data.action = 'update'
              data._id = this.skillInfo._id
            }
            this.loading = true
            if (!data.Strategy) {
              data.Strategy = 'rrmemory'
            }
            this.$store.dispatch('updateQueueForSkill', data).then(res => {
              this.loading = false
              if (res.success) {
                this.$emit('refresh', data.PBX)
                this.$emit('reload', false)
              } else {
                this.$emit('reload', true)
              }
            })
          } else {
            this.$message.error(this.$t('callServiceSkillGroup.callServiceSkillGroup52'))
          }
        })
      },
      refreshSounds () {
        this.ivrSoundOptions = []
        this.waitMusic = []
        this.sounds = this.$store.state.session.ivrMap[this.skillInfoForm.PBX].data.ivr_sound
        this.sounds.forEach(item => {
          if (item.SoundType === 'normal') {
            this.ivrSoundOptions.push(item)
          } else if (item.SoundType === 'hold') {
            this.waitMusic.push(item)
          }
        })
      },
      getCirculationInfo () {
        this.ToPeerTypeWhenQueueEmptyChange(this.skillInfo.ToPeerTypeWhenQueueEmpty)
        this.ToPeerTypeWhenWaitChange(this.skillInfo.ToPeerTypeWhenWait)
        this.ToPeerTypeWhenWaitTimeoutChange(this.skillInfo.ToPeerTypeWhenWaitTimeout)
        this.ToPeerTypeWhenHangupedChange(this.skillInfo.ToPeerTypeWhenHanguped)
      },
      initInfo () {
        this.$store.dispatch('getAssignNodesByPbx', {Account: this.$store.state.session.account.account, PBX: this.skillInfoForm.PBX, type: 'ivr_sound'}).then(res => {
          this.refreshSounds()
        })
      },
      initAgent () {
        this.$store.dispatch('getAssignNodesByPbx', {Account: this.$store.state.session.account.account, PBX: this.skillInfoForm.PBX, type: 'account_user'}).then(res => {
          if (this.isNewConfig) {
            this.isNewConfigAgent = true
          } else {
            this.isShowAgentAssign = true
          }
        })
      },
      getIsShowTrans () {
        this.$store.dispatch('getNewFeaturesReport', {pbx: this.skillInfoForm.PBX}).then((res)=>{
          if (res.data.features && res.data.features.indexOf('QueueNotTranfer') > -1) {
            this.isShowNotransfer = true
          } else {
            this.isShowNotransfer = false
          }
        })
      },
      initSelect () {
        this.getCirculationInfo()
      }
    },
    components: {
      AgentAssign,
      questionToolTip
    },
    mounted () {
      this.getIsShowTrans()
      this.getXbotList()
    },
    beforeMount () {
      let routes = this.$route.path.split('/')
      if (routes[2] === 'newConfig') { // 是新版设置
        this.isNewConfig = false
      } else {
        this.isNewConfig = false
      }
      this.pbxs = this.$store.state.session.account.pbx
      this.skillInfoForm.PBX = this.skillInfo.PBX || this.pbxs[0].PBX
      this.PBXForAgent = this.skillInfoForm.PBX
//        等待音乐   进入技能组提示音
      if (this.skillInfo.MusicClass) {
        this.skillInfoForm.MusicClass = this.skillInfo.MusicClass.split('.')[1] === 'wav' ? this.skillInfo.MusicClass : this.skillInfo.MusicClass + '.wav'
      } else {
        this.skillInfoForm.MusicClass = ''
      }
      if (this.skillInfo.Music) {
        this.skillInfoForm.Music = this.skillInfo.Music.split('.')[1] === 'wav' ? this.skillInfo.Music : this.skillInfo.Music + '.wav'
      } else {
        this.skillInfoForm.Music = ''
      }
//           流转部分 选择框的数据渲染
      this.ToPeerTypeWhenQueueEmptyOptions = this.systemPeerTypeArr
      this.ToPeerWhenWaitOptions = this.systemPeerTypeArr
      this.ToPeerWhenWaitTimeoutOptions = this.systemPeerTypeArr
      this.ToPeerWhenHangupedOptions = this.systemPeerTypeArr
      this.tabChange(1)
      this.skillInfoForm.ToPeerTypeWhenQueueEmpty = this.skillInfo.ToPeerTypeWhenQueueEmpty || 'system'
      // this.ToPeerTypeWhenQueueEmptyChange(this.skillInfo.ToPeerTypeWhenQueueEmpty)
      this.skillInfoForm.ToPeerWhenQueueEmpty = this.skillInfo.ToPeerWhenQueueEmpty || this.ToPeerTypeWhenQueueEmptyOptions[0].value
      this.skillInfoForm.ToPeerTypeWhenWait = this.skillInfo.ToPeerTypeWhenWait || 'system'
      // this.ToPeerTypeWhenWaitChange(this.skillInfo.ToPeerTypeWhenWait)
      this.skillInfoForm.ToPeerWhenWait = this.skillInfo.ToPeerWhenWait || this.ToPeerWhenWaitOptions[0].value
      this.skillInfoForm.ToPeerTypeWhenWaitTimeout = this.skillInfo.ToPeerTypeWhenWaitTimeout || 'system'
      // this.ToPeerTypeWhenWaitTimeoutChange(this.skillInfo.ToPeerTypeWhenWaitTimeout)
      this.skillInfoForm.ToPeerWhenWaitTimeout = this.skillInfo.ToPeerWhenWaitTimeout || this.ToPeerWhenWaitTimeoutOptions[0].value
      this.skillInfoForm.ToPeerTypeWhenHanguped = this.skillInfo.ToPeerTypeWhenHanguped || 'system'
      // this.ToPeerTypeWhenHangupedChange(this.skillInfo.ToPeerTypeWhenHanguped)
      this.skillInfoForm.ToPeerWhenHanguped = this.skillInfo.ToPeerWhenHanguped || this.ToPeerWhenHangupedOptions[0].value
      let p1 = this.$store.dispatch('getCache', {type: 'callUrls'})
      let p2 = this.$store.dispatch('getCache', {type: 'businessFlowOnly'})
//      let p3 = this.$store.dispatch('getCache', { type: 'agents' })
      Promise.all([p1, p2]).then(([callUrls, businessFlowOnly]) => {
        this.callUrls = callUrls
        this.businessFlowOnly = businessFlowOnly
//        this.agents = agentsData
        this.getAssignMembersArr()  //   分配座席 回显
        this.initInfo()   //   刷新等待音乐和提示音的数据源
        //      多个来电弹屏 处理
        this.skillInfoForm.CallinTypeId = []
        if (typeof (this.skillInfo.KfBussinessTypeId) === 'undefined') {   //  老版来电弹屏设置
          this.skillInfoForm.KfBussinessTypeId = this.skillInfo.BussinessTypeId || ''
          if (this.skillInfo.BussinessTypeId) {
            let interfaceId = this.skillInfo.BussinessTypeId.split('_')[1]
            for (let y = 0; y < this.callUrls.length; y++) {
              if (this.callUrls[y]._id === interfaceId) {
                this.skillInfoForm.KfBussinessTypeId = ''
                this.skillInfoForm.CallinTypeId.push(this.skillInfo.BussinessTypeId)
                break
              }
            }
          }
        } else {   //  新版来电弹屏设置
          this.skillInfoForm.KfBussinessTypeId = this.skillInfo.KfBussinessTypeId || ''
          for (let i = 0; i < this.callUrls.length; i++) {
            for (let j = 0; j < this.skillInfo.CallinTypeId.length; j++) {
              if (this.callUrls[i]._id === this.skillInfo.CallinTypeId[j].split('_')[1]) {
                this.skillInfoForm.CallinTypeId.push(this.skillInfo.CallinTypeId[j])
              }
            }
          }
//          this.skillInfoForm.CallinTypeId = this.skillInfo.CallinTypeId
        }
      })
    }
  }
</script>
<style lang="stylus">
.skill-group-item-ob-flex
  .skill-group-item-ob-flex-ipt
    margin-bottom 15px
  .el-input-number
    .el-input-number__increase
      height 15px
      top 4px
    .el-input-number__decrease
      bottom 4px
      height 15px
    .el-input__inner
      height 32px
.addOrEditCallServiceSkillGroup
  .assign
    .selecSate
      padding 0!important
      .scResult
        padding-left 0
        .result
          .el-input
            width 50px
</style>
<style lang="stylus" scoped>
  @import "../../../../../../assets/common.styl"
  .addOrEditCallServiceSkillGroup
    padding 20px
    .skill-group-item-row
      display flex
      align-items flex-start
    .skill-group-item-ob-flex
      .text
        box-sizing border-box
      p:nth-child(1)
        color #7888A7
      p:nth-child(2)
        padding 10px
        background #FDF6EC
        color #E8A94B
      display flex
      flex-direction column
    .skill-group-item
      width 220px
      display inline-block
      margin 0 20px 12px 0
    .el-form-item
      margin 0
    .el-input
      margin 5px 20px 0 0
    .el-select
      margin 5px 20px 3px 0
    .el-input,.el-select
      width 220px
    .el-radio-group
      margin 5px 0 16px 0
    .tab
      text-align center
      overflow hidden
      border-bottom 1px solid $c-border2
      .tab-item
        display inline-block
        cursor pointer
        padding-bottom 3px
        margin-right 10px
      .tab-item-active
        color $c-main
        border-bottom 2px solid $c-main
    .cont
      padding-top 20px
      padding-bottom 20px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
    .prompt
      color $c-prompt
      margin-bottom 20px
  .form_box
    max-height calc(100vh - 275px)
    overflow-y auto
  .btn_box
    overflow hidden
</style>
